package com.education.ai.service.impl;

import com.education.ai.dao.AbilityAssessmentDao;
import com.education.ai.entity.AbilityAssessment;
import com.education.ai.service.AbilityAssessmentService;
import com.education.ai.service.AiTeachingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 能力评估服务实现类
 */
@Service
public class AbilityAssessmentServiceImpl implements AbilityAssessmentService {

    @Autowired
    private AbilityAssessmentDao assessmentDao;
    
    @Autowired
    private AiTeachingService aiTeachingService;

    @Override
    public List<AbilityAssessment> getAllAssessments() {
        return assessmentDao.findAll();
    }

    @Override
    public Optional<AbilityAssessment> getAssessmentById(Long id) {
        return assessmentDao.findById(id);
    }

    @Override
    public List<AbilityAssessment> getAssessmentsByStudentId(String studentId) {
        return assessmentDao.findByStudentId(studentId);
    }

    @Override
    public List<AbilityAssessment> getAssessmentsBySubject(String subject) {
        return assessmentDao.findBySubject(subject);
    }

    @Override
    public List<AbilityAssessment> getAssessmentsByStudentIdAndSubject(String studentId, String subject) {
        return assessmentDao.findByStudentIdAndSubject(studentId, subject);
    }

    @Override
    public Optional<AbilityAssessment> getLatestAssessment(String studentId, String subject) {
        AbilityAssessment assessment = assessmentDao.findFirstByStudentIdAndSubjectOrderByAssessmentTimeDesc(
                studentId, subject);
        return Optional.ofNullable(assessment);
    }

    @Override
    @Transactional
    public AbilityAssessment saveAssessment(AbilityAssessment assessment) {
        return assessmentDao.save(assessment);
    }

    @Override
    @Transactional
    public void deleteAssessment(Long id) {
        assessmentDao.deleteById(id);
    }

    @Override
    public Map<String, Double> getSubjectAssessmentStatistics(String subject) {
        List<AbilityAssessment> assessments = assessmentDao.findBySubject(subject);
        
        if (assessments.isEmpty()) {
            return Collections.emptyMap();
        }
        
        Map<String, Double> statistics = new HashMap<>();
        
        // 获取平均分数据
        Object[] avgScores = assessmentDao.getAverageScoresBySubject(subject);
        
        if (avgScores != null && avgScores.length == 3) {
            if (avgScores[0] != null) {
                statistics.put("avgKnowledgeDimension", ((Number) avgScores[0]).doubleValue());
            }
            if (avgScores[1] != null) {
                statistics.put("avgApplicationDimension", ((Number) avgScores[1]).doubleValue());
            }
            if (avgScores[2] != null) {
                statistics.put("avgInnovationDimension", ((Number) avgScores[2]).doubleValue());
            }
        }
        
        // 计算每个维度的最高分和最低分
        Float maxKnowledge = assessments.stream()
                .map(AbilityAssessment::getKnowledgeDimension)
                .filter(Objects::nonNull)
                .max(Float::compare)
                .orElse(0.0f);
        statistics.put("maxKnowledgeDimension", maxKnowledge.doubleValue());
        
        Float minKnowledge = assessments.stream()
                .map(AbilityAssessment::getKnowledgeDimension)
                .filter(Objects::nonNull)
                .min(Float::compare)
                .orElse(0.0f);
        statistics.put("minKnowledgeDimension", minKnowledge.doubleValue());
        
        Float maxApplication = assessments.stream()
                .map(AbilityAssessment::getApplicationDimension)
                .filter(Objects::nonNull)
                .max(Float::compare)
                .orElse(0.0f);
        statistics.put("maxApplicationDimension", maxApplication.doubleValue());
        
        Float minApplication = assessments.stream()
                .map(AbilityAssessment::getApplicationDimension)
                .filter(Objects::nonNull)
                .min(Float::compare)
                .orElse(0.0f);
        statistics.put("minApplicationDimension", minApplication.doubleValue());
        
        Float maxInnovation = assessments.stream()
                .map(AbilityAssessment::getInnovationDimension)
                .filter(Objects::nonNull)
                .max(Float::compare)
                .orElse(0.0f);
        statistics.put("maxInnovationDimension", maxInnovation.doubleValue());
        
        Float minInnovation = assessments.stream()
                .map(AbilityAssessment::getInnovationDimension)
                .filter(Objects::nonNull)
                .min(Float::compare)
                .orElse(0.0f);
        statistics.put("minInnovationDimension", minInnovation.doubleValue());
        
        return statistics;
    }
    
    @Override
    @Transactional
    public AbilityAssessment generateAssessment(String studentId, String subject) {
        // 调用AI服务生成能力评估
        Map<String, Object> assessmentData = aiTeachingService.generateAbilityAssessment(studentId, subject);
        
        AbilityAssessment assessment = new AbilityAssessment();
        assessment.setStudentId(studentId);
        assessment.setSubject(subject);
        
        // 从AI返回的数据中提取能力评估分数
        if (assessmentData.containsKey("knowledge_dimension")) {
            float score = ((Number) assessmentData.get("knowledge_dimension")).floatValue();
            assessment.setKnowledgeDimension(score);
        }
        
        if (assessmentData.containsKey("application_dimension")) {
            float score = ((Number) assessmentData.get("application_dimension")).floatValue();
            assessment.setApplicationDimension(score);
        }
        
        if (assessmentData.containsKey("innovation_dimension")) {
            float score = ((Number) assessmentData.get("innovation_dimension")).floatValue();
            assessment.setInnovationDimension(score);
        }
        
        if (assessmentData.containsKey("assessment_details")) {
            assessment.setAssessmentDetails((String) assessmentData.get("assessment_details"));
        }
        
        if (assessmentData.containsKey("recommendation")) {
            assessment.setRecommendation((String) assessmentData.get("recommendation"));
        }
        
        // 保存评估结果
        return saveAssessment(assessment);
    }
} 